package cn.learn.async.restful;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.annotation.Resource;
import java.util.concurrent.Callable;

/**
 * 使用异步线程提供服务
 * 使用Runnable异常处理Rest服务
 *
 * 使用DeferredResult异步处理Rest服务
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年08月19日21:42
 */
@Slf4j
@RestController
@RequestMapping("async/rest/web")
public class AsyncRestWebController {

    @GetMapping("/order1")
    public Callable<String> order1() {
        log.info("主线程开始");
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("副线程开始");
                Thread.sleep(1000);
                log.info("副线程结束");
                return getData() + "order1";
            }
        };
        log.info("主线程结束");
        return callable;
    }

    @Resource
    private MockQueue mockQueue;
    @Resource
    private DeferredResultHolder deferredResultHolder;

    @GetMapping("/order2")
    public DeferredResult<String> order2() {
        log.info("主线程开始");
        String orderNumber = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNumber);

        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber,result);
        log.info("主线程结束");
        return result;
    }

    @GetMapping("/order3")
    public DeferredResult<String> order3() {
        log.info("主线程开始");

        DeferredResult<String> result = new DeferredResult<>();
        result.setResult(getData());
        log.info("主线程结束");
        return result;
    }

    @SneakyThrows
    private String getData() {
        Thread.sleep(2000);
        log.info("暂停");
        return "成功";
    }

}
